package com.yaowk.weixin.controller;

import com.feizhou.swagger.annotation.Api;
import com.feizhou.swagger.annotation.ApiOperation;
import com.feizhou.swagger.annotation.Param;
import com.feizhou.swagger.annotation.Params;
import com.jfinal.aop.Before;
import com.jfinal.weixin.sdk.api.ApiResult;
import com.jfinal.weixin.sdk.api.MediaApi;
import com.yaowk.common.model.base.Page;
import com.yaowk.system.validator.PlatformIdValidator;

import java.io.File;

/**
 * Created by yaowk on 17-8-1.
 */
@Api(tag = "material", description = "素材管理", url = "/admin/weixin/material")
@Before(PlatformIdValidator.class)
public class MaterialController extends BaseApiController {

    @ApiOperation(description = "查询永久素材列表", url = "/list")
    @Params({
            @Param(name = "platformId", description = "平台id", required = true),
            @Param(name = "msgType", description = "素材类型", required = true),
            @Param(name = "pageSize", description = "分页大小", defaultValue = "20"),
            @Param(name = "pageNumber", description = "当前页", defaultValue = "1")
    })
    public void list() {
        String msgType = getPara("msgType");
        Page page = getPage();
        ApiResult apiResult = MediaApi.batchGetMaterial(MediaApi.MediaType.valueOf(msgType), (page.getPageNumber() - 1) * page.getPageSize(), page.getPageSize());
        renderJson(apiResult);
    }

    @ApiOperation(description = "新增永久素材", url = "/add")
    @Params({
            @Param(name = "platformId", description = "平台id", required = true),
            @Param(name = "msgType", description = "素材类型", required = true),
            @Param(name = "real_path", description = "真实路径", required = true),
            @Param(name = "title", description = "视频素材的标题"),
            @Param(name = "introduction", description = "视频素材的描述")
    })
    public void add() {
        MediaApi.MediaType msgType = MediaApi.MediaType.valueOf("msgType");
        File file = new File(getPara("real_path"));
        ApiResult result = null;
        if (file.exists() && file.isFile()) {
            // 如果是视频类型
            if (MediaApi.MediaType.VIDEO.equals(msgType)) {
                result = MediaApi.addMaterial(file, getPara("title"), getPara("introduction"));
            } else {
                result = MediaApi.addMaterial(file, msgType);
            }
        }
        renderJson(result);
    }

    @ApiOperation(description = "删除永久素材", url = "/delete")
    @Params({
            @Param(name = "platformId", description = "平台id", required = true),
            @Param(name = "mediaId", description = "素材id", required = true),
    })
    public void delete() {
        String mediaId = getPara("mediaId");
        ApiResult apiResult = MediaApi.delMaterial(mediaId);
        renderJson(apiResult);
    }
}
